package com.winit.openapi.mms.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.spi.context.CommandContext;
import com.winit.cwm.spi.csi.command.QueryOrderNoForWaitInspectionCommand;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.ims.spi.SingleItemService;
import com.winit.ims.spi.inventory.InventoryService;
import com.winit.ims.spi.inventory.command.QueryOnOrderInventoryCommand;
import com.winit.ims.spi.inventory.command.UpdateInventoryForReturnCommand;
import com.winit.mms.spi.v2.command.CodeCommand;
import com.winit.mms.spi.v2.command.IdCommand;
import com.winit.mms.spi.v2.exception.MMSException;
import com.winit.mms.spi.v2.item.ItemService;
import com.winit.mms.spi.v2.item.command.AddItemReturnCommand;
import com.winit.mms.spi.v2.item.command.BatchModifySkuCodeThirdCommand;
import com.winit.mms.spi.v2.item.command.BatchModifySkuInternetSiteCommand;
import com.winit.mms.spi.v2.item.command.ExportSkuShelfStrategyCommand;
import com.winit.mms.spi.v2.item.command.GetByOriginalCodeCommand;
import com.winit.mms.spi.v2.item.command.GetItemBarcodeCommand;
import com.winit.mms.spi.v2.item.command.ImportSkuShelfStrategyCommand;
import com.winit.mms.spi.v2.item.command.ItemCodeCommand;
import com.winit.mms.spi.v2.item.command.ModifyClearItemSpecificationCommand;
import com.winit.mms.spi.v2.item.command.ModifyItemReturnCommand;
import com.winit.mms.spi.v2.item.command.ModifySkuShelfStrategyCommand;
import com.winit.mms.spi.v2.item.command.PageItemByCountryCodeCommand;
import com.winit.mms.spi.v2.item.command.PageItemReturnsCommand;
import com.winit.mms.spi.v2.item.command.PageItemsCommand;
import com.winit.mms.spi.v2.item.command.PageItemsForOpenApiCommand;
import com.winit.mms.spi.v2.item.command.PageMmsItemCommand;
import com.winit.mms.spi.v2.item.command.QueryItemCommand;
import com.winit.mms.spi.v2.item.command.QueryItemReturnByCodeCommand;
import com.winit.mms.spi.v2.item.command.QueryItemReturnBySkuCodeCommand;
import com.winit.mms.spi.v2.item.command.QueryItemsCommand;
import com.winit.mms.spi.v2.item.command.QueryItemsForOrderCommand;
import com.winit.mms.spi.v2.item.command.QueryLikeSkuCodeCommand;
import com.winit.mms.spi.v2.item.command.QueryMMSItemCommand;
import com.winit.mms.spi.v2.item.command.QueryMmsItemDetailCommand;
import com.winit.mms.spi.v2.item.command.ReceiveRecommendDeclareInfoCommand;
import com.winit.mms.spi.v2.item.command.SupplyItemReturnCommand;
import com.winit.mms.spi.v2.item.command.UpdateMmsItemActiveCommand;
import com.winit.mms.spi.v2.item.command.UpdateMmsItemsCommand;
import com.winit.mms.spi.v2.item.command.UpdateMmsReturnItemActiveCommand;
import com.winit.mms.spi.v2.item.command.UpdateMmsReturnItemsCommand;
import com.winit.mms.spi.v2.item.command.export.AddItemExportCommand;
import com.winit.mms.spi.v2.item.command.export.ImportItemExportsCommand;
import com.winit.mms.spi.v2.item.command.export.ModifyItemExportCommand;
import com.winit.mms.spi.v2.item.command.export.QueryItemExportsPageCommand;
import com.winit.mms.spi.v2.item.command.export.QueryItemsForISPOrderCommand;
import com.winit.mms.spi.v2.item.command.export.RemoveItemsExportCommand;
import com.winit.mms.spi.v2.item.vo.AddItemReturnVo;
import com.winit.mms.spi.v2.item.vo.ItemImageVo;
import com.winit.mms.spi.v2.item.vo.ItemPagesVo;
import com.winit.mms.spi.v2.item.vo.ItemReturnDetailVo;
import com.winit.mms.spi.v2.item.vo.ItemReturnPagesVo;
import com.winit.mms.spi.v2.item.vo.ItemReturnVo;
import com.winit.mms.spi.v2.item.vo.ItemSetUpShelfCountVo;
import com.winit.mms.spi.v2.item.vo.ItemShelfStrategyVo;
import com.winit.mms.spi.v2.item.vo.ItemVo;
import com.winit.mms.spi.v2.item.vo.MmsItemDetailVo;
import com.winit.mms.spi.v2.item.vo.PageItemByCountryCodeVo;
import com.winit.mms.spi.v2.item.vo.PageItemForOpenApiVo;
import com.winit.mms.spi.v2.item.vo.PageItemVo;
import com.winit.mms.spi.v2.item.vo.PageVo;
import com.winit.mms.spi.v2.item.vo.QueryItemReturnByCodeVo;
import com.winit.mms.spi.v2.item.vo.QueryItemReturnBySkuCodeVo;
import com.winit.mms.spi.v2.item.vo.export.ItemExportPageVo;
import com.winit.mms.spi.v2.item.vo.export.ItemExportVo;
import com.winit.mms.spi.v2.mt.command.ModifyItemForSellerCommand;
import com.winit.mms.spi.v2.mt.command.ModifyItemInfomationCommand;
import com.winit.mms.spi.v2.mt.command.RegisterItemCommand;
import com.winit.mms.spi.v2.mt.vo.ImportCheckErrorMessagesVO;
import com.winit.oms.spi.gt.GlobalTransferOrderValidateService;
import com.winit.oms.spi.gt.vo.GlobalTransferOrder;
import com.winit.oms.spi.inbound.InboundOrderService;
import com.winit.oms.spi.inbound.command.GlobalTransferOrderPackagelineCommand;
import com.winit.oms.spi.inbound.command.MerchandiseOrderCommand;
import com.winit.oms.spi.inbound.vo.InboundOrderVo;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ContextUtils;
import com.winit.openapi.util.PDFBox4MergePDF;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ums.spi.UmsCustomerService;
import com.winit.ums.spi.commnad.QueryCustomerByCBpartnerIdCommand;
import com.winit.ums.spi.commnad.customer.QueryCompanylCommand;
import com.winit.ums.spi.vo.CustomerInfoVO;

/**
 * 商品Controller
 * 
 * @author qibin.tang
 */
@Controller 
@RequestMapping(value = "/mms/item")
public class ItemController extends BaseController {

    /**
     * 商品服务
     */
    @Resource
    private ItemService        itemService;

    /**
     * ums客户信息
     */
    @Resource
    private UmsCustomerService umsCustomerService;
    
    @Resource
    private InventoryService   inventoryService;
    
    @Resource
    private InboundOrderService   inboundOrderService;
	@Resource
    private SingleItemService  singleItemService;
	
	@Resource
	private GlobalTransferOrderValidateService  globalTransferOrderValidateService;
	@Resource
	private com.winit.cwm.spi.csi.InboundOrderService csiInboundOrderService;


	
    /**
     * 根据客户编码，SKU编码，规格查询商品
     *    
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItem")
    public String queryItem(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            QueryItemCommand command = buildQueryItemCommand(json);
            QueryCompanylCommand queryCompanylCommand = new QueryCompanylCommand();
            queryCompanylCommand.setEmail(command.getCtx().getUsername());
            CustomerInfoVO customerInfoVO = umsCustomerService.queryCompanyByUserName(queryCompanylCommand);
            if (customerInfoVO == null) {
                throw new ApiException(ErrorCode.USER_NOT_FOUND);
            }
            command.setCustomerCode(customerInfoVO.getCode());

            ItemVo itemVo = itemService.queryItemBySkuAndCustomerCode(command);
            responseMsg.setData(itemVo);
        }
        return SUCCESS;
    }

    /**
     * 构建查询商品Command
     * 
     * @param json
     * @return
     */
    private QueryItemCommand buildQueryItemCommand(JSONObject json) {
        QueryItemCommand command = new QueryItemCommand();
        command.setCtx(CommandContext.getContext());
        command.setCustomerCode(CommandContext.getContext().getUserId());
        if (json.containsKey("skuCode")) {
            command.setSkuCode(json.getString("skuCode"));
        }
        if (json.containsKey("specification")) {
            command.setSpecification(json.getString("specification"));
        }
        return command;
    }

    /**
     * 根据客户编码，管理方式
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItems")
    public String queryItemBaseInfo(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryItemsCommand command = JSON.parseObject(requestMsg.getData().toString(), QueryItemsCommand.class);
        command.setCtx(CommandContext.getContext());
        List<ItemVo> list = itemService.queryItems(command);
        responseMsg.setData(list);
        return SUCCESS;
    }

    /**
     * 根据客户编码查询商品列表
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemListByCustomerCode")
    public String queryItemListByCustomerCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        CodeCommand command = JSON.parseObject(requestMsg.getData().toString(), CodeCommand.class);
        command.setCode(this.getContextCustomerInfo().getCode());
        List<ItemVo> list = itemService.queryItemByCustomerCode(command);
        responseMsg.setData(list);
        return SUCCESS;
    }

    /**
     * 根据客户编码，头程类型，winit产品编码，仓库CODE查询商品信息
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemsForOrder")
    public String queryItemsForOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryItemsForOrderCommand command = JSON.parseObject(requestMsg.getData().toString(),
            QueryItemsForOrderCommand.class);
        command.setCtx(CommandContext.getContext());

        QueryCompanylCommand queryCompanylCommand = new QueryCompanylCommand();
        queryCompanylCommand.setEmail(command.getCtx().getUsername());
        CustomerInfoVO customerInfoVO = umsCustomerService.queryCompanyByUserName(queryCompanylCommand);
        if (customerInfoVO == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND);
        }
        command.setCustomerCode(customerInfoVO.getCode());

        List<ItemVo> list = itemService.queryItemsForOrder(command);
        responseMsg.setData(list);
        return SUCCESS;
    }

    /**
     * 根据sku,规格返回商品条形码
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getItemBarcode")
    public String getItemBarcode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        GetItemBarcodeCommand command = JSON.parseObject(requestMsg.getData().toString(), GetItemBarcodeCommand.class);
        command.setCtx(CommandContext.getContext());
        List<String> bytes = itemService.getItemBarcode(command);
        PDFBox4MergePDF tool = new PDFBox4MergePDF();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            List<byte[]> byteList = tool.decryptBASE64(bytes);
            tool.merge(byteList, out);
        } catch (IOException e) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        Map<String, Object> dataMap = new HashMap<String, Object>();
        String mergeByte = tool.base64Encode(out.toByteArray());

        if (mergeByte != null && mergeByte.length() > 0) {
            dataMap.put("files", mergeByte);
        }
        responseMsg.setData(dataMap);
        return SUCCESS;
    }

    /**
     * 根据sku,规格返回商品条形码
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemeImageByCode")
    public String queryItemeImageByCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ItemCodeCommand command = JSON.parseObject(requestMsg.getData().toString(), ItemCodeCommand.class);
        command.setCtx(CommandContext.getContext());
        List<ItemImageVo> list = itemService.queryItemeImageByCode(command);
        responseMsg.setData(list);
        return SUCCESS;
    }

    /**
     * 根据退货商品ID查询退货商品详情
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemeReturnDetail")
    public String queryItemeReturnDetail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        IdCommand command = JSON.parseObject(requestMsg.getData().toString(), IdCommand.class);
        command.setCtx(CommandContext.getContext());
        ItemReturnDetailVo itemReturnDetailVo = itemService.queryItemeReturnDetail(command);
        responseMsg.setData(itemReturnDetailVo);
        return SUCCESS;
    }

    /**
     * 根据国家查询商品列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/pageItemByCountryCode")
    public String pageItemByCountryCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        PageItemByCountryCodeCommand command = JSON.parseObject(requestMsg.getData().toString(), PageItemByCountryCodeCommand.class);
        command.setCtx(CommandContext.getContext());

        PageVo pageVo = new PageVo();
        
        Object params = requestMsg.getData();

        JSONObject json = null;
        if (params instanceof JSONObject) {
            json = (JSONObject) params;
            int pageNo = 1, pageSize = 10; // 分页参数
            if (ValidateUtil.isExistValue(json, "pageParams")) {
                JSONObject pageParam = json.getJSONObject("pageParams");
                if (ValidateUtil.isExistValue(pageParam, "pageNo")) {
                    pageNo = pageParam.getIntValue("pageNo") == 0 ? 1 : pageParam.getIntValue("pageNo");

                }
                if (ValidateUtil.isExistValue(pageParam, "pageSize")) {
                    pageSize = pageParam.getIntValue("pageSize");
                }
            }
            pageVo.setPageNo(pageNo);
            pageVo.setPageSize(pageSize);
            command.setPageVo(pageVo);
        } else {
            throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING);
        }
        
        QueryCompanylCommand queryCompanylCommand = new QueryCompanylCommand();
        queryCompanylCommand.setEmail(command.getCtx().getUsername());
        CustomerInfoVO customerInfoVO = umsCustomerService.queryCompanyByUserName(queryCompanylCommand);
        if (customerInfoVO == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND);
        }
        command.setCustomerCode(customerInfoVO.getCode());

        Page<PageItemByCountryCodeVo> list = itemService.pageItemByCountryCode(command);

        if (list != null) {
            Map<String, Object> pageMap = getPageParams(list);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", list.getContent());
            data.put("pageParams", pageMap.get("pageParams"));
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
    
    
    @RequestMapping(value = "/pageItemReturns")
    public String pageItemReturns(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        PageItemReturnsCommand command = JSON.parseObject(requestMsg.getData().toString(), PageItemReturnsCommand.class);
        command.setCtx(CommandContext.getContext());

        PageVo pageVo = new PageVo();
        
        Object params = requestMsg.getData();

        JSONObject json = null;
        if (params instanceof JSONObject) {
            json = (JSONObject) params;
            int pageNo = 1, pageSize = 10; // 分页参数
            if (ValidateUtil.isExistValue(json, "pageParams")) {
                JSONObject pageParam = json.getJSONObject("pageParams");
                if (ValidateUtil.isExistValue(pageParam, "pageNo")) {
                    pageNo = pageParam.getIntValue("pageNo") == 0 ? 1 : pageParam.getIntValue("pageNo");

                }
                if (ValidateUtil.isExistValue(pageParam, "pageSize")) {
                    pageSize = pageParam.getIntValue("pageSize");
                }
            }
            pageVo.setPageNo(pageNo);
            pageVo.setPageSize(pageSize);
            command.setPageVo(pageVo);
        } else {
            throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING);
        }
        
        
        QueryCompanylCommand queryCompanylCommand = new QueryCompanylCommand();
        queryCompanylCommand.setEmail(command.getCtx().getUsername());
        CustomerInfoVO customerInfoVO = umsCustomerService.queryCompanyByUserName(queryCompanylCommand);
        if (customerInfoVO == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND);
        }
        command.setCustomerCode(customerInfoVO.getCode());

        Page<ItemReturnPagesVo> list = itemService.findReturnItemPage(command);

        if (list != null) {
            List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
            for (ItemReturnPagesVo itemReturnPagesVo : list.content) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", itemReturnPagesVo.getId());
                map.put("code", itemReturnPagesVo.getCode());
                map.put("customerName", itemReturnPagesVo.getCustomerName());
                map.put("customerCode", itemReturnPagesVo.getCustomerCode());
                map.put("type", itemReturnPagesVo.getType());
                map.put("skuCode", itemReturnPagesVo.getSkuCode());
                map.put("cnName", itemReturnPagesVo.getCnName());
                map.put("name", itemReturnPagesVo.getName());
                map.put("length", itemReturnPagesVo.getLength());
                map.put("height", itemReturnPagesVo.getHeight());
                map.put("width", itemReturnPagesVo.getWidth());
                map.put("volume", itemReturnPagesVo.getVolume());
                map.put("weight", itemReturnPagesVo.getWeight());
                map.put("registerWeight", itemReturnPagesVo.getRegisterWeight());
                map.put("registerLength", itemReturnPagesVo.getRegisterLength());
                map.put("registerWidth", itemReturnPagesVo.getRegisterWidth());
                map.put("registerHeight", itemReturnPagesVo.getRegisterHeight());
                map.put("registerVolume", itemReturnPagesVo.getRegisterVolume());
                map.put("specification", itemReturnPagesVo.getSpecification());
                map.put("importPrice", itemReturnPagesVo.getImportPrice());
                map.put("originalCode", itemReturnPagesVo.getOriginalCode());
                map.put("isActive", itemReturnPagesVo.getIsActive());
                datalist.add(map);
            }
            Map<String, Object> pageMap = getPageParams(list);

            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", datalist);
            data.put("pageParams", pageMap.get("pageParams"));
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 根据sku查询退货商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemReturnBySkuCode")
    public String queryItemReturnBySkuCode(@ModelAttribute RequestMsg requestMsg,
                                           @ModelAttribute ResponseMsg responseMsg) {
        QueryItemReturnBySkuCodeCommand command = JSON.parseObject(requestMsg.getData().toString(),
            QueryItemReturnBySkuCodeCommand.class);
        command.setCtx(CommandContext.getContext());

        QueryCompanylCommand queryCompanylCommand = new QueryCompanylCommand();
        queryCompanylCommand.setEmail(command.getCtx().getUsername());
        CustomerInfoVO customerInfoVO = umsCustomerService.queryCompanyByUserName(queryCompanylCommand);
        if (customerInfoVO == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND);
        }
        command.setCustomerCode(customerInfoVO.getCode());

        QueryItemReturnBySkuCodeVo queryItemReturnBySkuCodeVo = itemService.queryItemReturnBySkuCodeAndCustomerCode(command);
        responseMsg.setData(queryItemReturnBySkuCodeVo);
        return SUCCESS;
    }

    /**
     * 添加退货商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/addItemReturn")
    public String addItemReturn(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AddItemReturnCommand command = JSON.parseObject(requestMsg.getData().toString(), AddItemReturnCommand.class);
        command.setCtx(CommandContext.getContext());
        AddItemReturnVo addItemReturnVo = itemService.addReturnItem(command);
        responseMsg.setData(addItemReturnVo);
        return SUCCESS;
    }

    /**
     * 删除退货商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/deleteItemReturn")
    public String deleteItemReturn(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        IdCommand command = JSON.parseObject(requestMsg.getData().toString(), IdCommand.class);
        command.setCtx(CommandContext.getContext());
        itemService.deleteItemReturn(command);
        return SUCCESS;
    }

    /**
     * 修改退货商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/modifyItemReturn")
    public String modifyItemReturn(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ModifyItemReturnCommand command = JSON.parseObject(requestMsg.getData().toString(),
            ModifyItemReturnCommand.class);
        command.setCtx(CommandContext.getContext());
        itemService.modifyItemReturn(command);
        return SUCCESS;
    }

    /**
     * 出口商品导入
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/addItemExports")
    public String addItemExports(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            JSONArray array = json.getJSONArray("itemExportList");
            if (array == null || array.size() == 0) {
                throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "itemExportList");
            }
            ImportItemExportsCommand commands = new ImportItemExportsCommand();
            QueryCompanylCommand userCommand = new QueryCompanylCommand();
            userCommand.setEmail(CommandContext.getContext().getUsername());
            // 获取客户编码
            CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
            List<AddItemExportCommand> list = new ArrayList<AddItemExportCommand>();
            if (customer == null || customer.getCode() == null) {
                throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
            }
            for (Object o : array) {
                JSONObject jo = (JSONObject) o;
                AddItemExportCommand command = new AddItemExportCommand();
                command.setCustomerCode(customer.getCode());
                command.setCustomerName(customer.getName());
                command.setName(jo.getString("name"));
                if (ValidateUtil.isNullOrEmpty(command.getName())) {
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, "Declared Name (Eng)");
                }
                command.setCnName(jo.getString("cnName"));
                if (ValidateUtil.isNullOrEmpty(command.getCnName())) {
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, "Declared Name (Chn)");
                }
                command.setSkuCode(jo.getString("skuCode"));
                if (ValidateUtil.isNullOrEmpty(command.getSkuCode())) {
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, "SKU NO.");
                }
                command.setDeclaredPrice(jo.getDouble("declaredPrice"));
                if (command.getDeclaredPrice() == null) {
                    throw new ApiException(ErrorCode.FIELD_NOT_NULL, "Declared Value (USD)");
                }
                command.setCtx(CommandContext.getContext());
                list.add(command);
            }
            commands.setItemExportList(list);
            List<String> errorList = itemService.addItemExports(commands);
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("errorList", errorList);
            responseMsg.setData(dataMap);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        return SUCCESS;
    }

    /**
     * 出口商品注册
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/addItemExport")
    public String addItemExport(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        AddItemExportCommand command = JSON.parseObject(requestMsg.getData().toString(), AddItemExportCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        command.setCustomerName(customer.getName());
        itemService.addItemExport(command);
        return SUCCESS;
    }

    /**
     * 查询出口商品详情
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemExport")
    public String queryItemExport(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        IdCommand command = JSON.parseObject(requestMsg.getData().toString(), IdCommand.class);
        command.setCtx(CommandContext.getContext());
        ItemExportVo vo = itemService.queryItemExportById(command);
        responseMsg.setData(vo);
        return SUCCESS;
    }

    /**
     * 编辑出口商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/modifyItemExport")
    public String modifyItemExport(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ModifyItemExportCommand command = JSON.parseObject(requestMsg.getData().toString(),
            ModifyItemExportCommand.class);
        command.setCtx(CommandContext.getContext());
        itemService.modifyItemExport(command);
        return SUCCESS;
    }

    /**
     * 删除出口商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/removeItemExport")
    public String removeItemExport(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        IdCommand command = JSON.parseObject(requestMsg.getData().toString(), IdCommand.class);
        command.setCtx(CommandContext.getContext());
        itemService.removeItemExport(command);
        return SUCCESS;
    }
    
    
    /**
     * 批量删除出口商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchRemoveItemExport")
    public String batchRemoveItemExport(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        RemoveItemsExportCommand command = JSON.parseObject(requestMsg.getData().toString(), RemoveItemsExportCommand.class);
        List<Long> ids = command.getIds();
        command.setIds(ids);
        command.setCtx(CommandContext.getContext());
        //获取customerCode
        QueryCustomerByCBpartnerIdCommand cusCommand = new QueryCustomerByCBpartnerIdCommand();
        cusCommand.setcBpartnerId(Long.parseLong(CommandContext.getContext().getUserId()));
        CustomerInfoVO customerInfoVO = umsCustomerService.queryCustomerByCBpartnerId(cusCommand);
        if (customerInfoVO == null || customerInfoVO.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customerInfoVO.getCode());
        itemService.removeItemsExport(command);
        return SUCCESS;
    }
    

    /**
     * 出口商品列表
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemExports")
    public String queryItemExports(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryItemExportsPageCommand command = JSON.parseObject(requestMsg.getData().toString(),
            QueryItemExportsPageCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        Page<ItemExportPageVo> page = itemService.pageItemExports(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * ISP下单查询接口
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemForISPOrder")
    public String queryItemForISPOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        QueryItemsForISPOrderCommand command = JSON.parseObject(requestMsg.getData().toString(),
            QueryItemsForISPOrderCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        List<ItemExportVo> listVo = itemService.queryItemsForISPOrder(command);
        responseMsg.setData(listVo);
        return SUCCESS;
    }

    /**
     * 根据客户编码,产品编码，规格批量修改第三方编码
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/batchModifySkuCodeThird")
    public String batchModifySkuCodeThird(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        BatchModifySkuCodeThirdCommand command = JSON.parseObject(requestMsg.getData().toString(),
            BatchModifySkuCodeThirdCommand.class);
        command.setCtx(CommandContext.getContext());
        Bpartner bpartner = command.getCtx().get(ApiConstant.API_BPARTNER);
        command.setCustomerCode(bpartner.getValue());
        List<String> checkErrorMessages = itemService.batchModifySkuCodeThird(command);
        responseMsg.setData(checkErrorMessages);
        return SUCCESS;
    }
    
    /**
     * 
     * MMS3.0商品信息列表
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryMmsItems")
    public String queryMmsItems(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        PageMmsItemCommand command = JSON.parseObject(requestMsg.getData().toString(),PageMmsItemCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        Page<PageItemVo> page = itemService.pageMmsItems(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
    
    
    
    /**
     * 
     * MMS3.0快捷注册商品列表
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryMmsRegisterItems")
    public String queryMmsRegisterItems(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        PageMmsItemCommand command = JSON.parseObject(requestMsg.getData().toString(),PageMmsItemCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        Page<PageItemVo> page = itemService.pageMmsRegisterItems(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
    
    
    
    /**
     * 
     * MMS3.0商品详情列表
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryMmsItemDetail")
    public String queryMmsItemDetail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        QueryMmsItemDetailCommand command = JSON.parseObject(requestMsg.getData().toString(),QueryMmsItemDetailCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        MmsItemDetailVo vo= itemService.queryMmsItemDetail(command);
        //只允许查看本人的商品信息
        if(vo != null && vo.getItemVo() != null) {
            if(customer.getCode().equals(vo.getItemVo().getCustomerCode())) {            
                responseMsg.setData(vo);
            }
        }
        return SUCCESS;
    }
    
    /**
     * 
     * MMS3.0导出商品
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/exportMmsItems")
    public String exportMmsItems(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        PageMmsItemCommand command = JSON.parseObject(requestMsg.getData().toString(),PageMmsItemCommand.class);
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        List<PageItemVo> vos= itemService.exportMmsItems(command);
        responseMsg.setData(vos);
        return SUCCESS;
    }

    
    /**
     * MMS3.0卖家网站修改商品
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/modifyItemForSeller")
    public String modifyItemForSeller(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ModifyItemForSellerCommand command = JSON.parseObject(requestMsg.getData().toString(),
            ModifyItemForSellerCommand.class);
        
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        command.setCustomerName(customer.getName());
      
        
        List<ImportCheckErrorMessagesVO> result = itemService.modifyItemForSeller(command);
        responseMsg.setData(result);
        return SUCCESS;
    }
    
    /**
     * MMS3.0
     * 为了替换erp中的com.winit.api.service.impl.ProductInfoServiceImpl.getProductInfomation
     * 具体给谁调用，目前暂时不知道
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getProductInfomation")
    public String getProductInfomation(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        JSONObject json = JSON.parseObject(requestMsg.getData().toString());
        if(json != null){
            QueryItemCommand command = new QueryItemCommand();
            command.setCtx(CommandContext.getContext());
            QueryCompanylCommand userCommand = new QueryCompanylCommand();
            userCommand.setEmail(CommandContext.getContext().getUsername());
            // 获取客户编码
            CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
            if (customer == null || customer.getCode() == null) {
                throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
            }
            command.setCustomerCode(customer.getCode());
            command.setSkuCode(json.getString("productCode"));
            command.setSpecification(json.getString("specification"));
            command.setCountryCode(json.getString("state"));
            List<Map<String,Object>> list = itemService.getItemByKeyAndCountry(command);
            responseMsg.setData(list);
        }
        return SUCCESS;
    }
    
    @RequestMapping(value = "/registerItem")
    public String registerProduct(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        RegisterItemCommand command = JSON.parseObject(requestMsg.getData().toString(),RegisterItemCommand.class);
        command.setCtx(CommandContext.getContext());
        
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        command.setCustomerName(customer.getName());
        
        itemService.registerItem(command);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/modifyItemInfomation")
    public String modifyItemInfomation(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        ModifyItemInfomationCommand command = JSON.parseObject(requestMsg.getData().toString(),ModifyItemInfomationCommand.class);
        command.setCtx(CommandContext.getContext());
        
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        // 获取客户编码
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if (customer == null || customer.getCode() == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND, CommandContext.getContext().getUsername());
        }
        command.setCustomerCode(customer.getCode());
        command.setCustomerName(customer.getName());
        
        List<ImportCheckErrorMessagesVO> errorMessagesVOs = itemService.modifyItemInfomation(command);
        responseMsg.setData(errorMessagesVOs);
        return SUCCESS;
    }
    
    /**
     * 补充退货商品信息
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/supplyItemReturn")
    public String supplyItemReturn(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        SupplyItemReturnCommand command = JSON.parseObject(requestMsg.getData().toString(),
            SupplyItemReturnCommand.class);
        command.setCtx(CommandContext.getContext());
        Bpartner bpartner = command.getCtx().get(ApiConstant.API_BPARTNER);
        command.setCustomerCode(bpartner.getValue());
        command.setCtx(CommandContext.getContext());
        itemService.supplyItemReturn(command);
        
        //退货商品维护成原SKU，需将IMS库存里商品信息修改
        QueryItemReturnByCodeCommand queryItemReturnByCodeCommand = new QueryItemReturnByCodeCommand();
        queryItemReturnByCodeCommand.setCode(command.getCode());
        QueryItemReturnByCodeVo queryItemReturnByCodeVo = itemService.queryItemReturnByCode(queryItemReturnByCodeCommand);
        UpdateInventoryForReturnCommand updateInventoryForReturnCommand = new UpdateInventoryForReturnCommand();
        updateInventoryForReturnCommand.setCtx(command.getCtx());
    	updateInventoryForReturnCommand.setMerchandiseCode(queryItemReturnByCodeVo.getSkuCode());
    	updateInventoryForReturnCommand.setMerchandiseEnName(queryItemReturnByCodeVo.getName());
    	updateInventoryForReturnCommand.setMerchandiseName(queryItemReturnByCodeVo.getCnName());
    	updateInventoryForReturnCommand.setSpecification(queryItemReturnByCodeVo.getSpecification());
    	updateInventoryForReturnCommand.setMerchandiseSerno(command.getCode());
    	updateInventoryForReturnCommand.setCustomerCode(command.getCustomerCode());
    	updateInventoryForReturnCommand.setIsMaintainMerchandise("N");
    	updateInventoryForReturnCommand.setIsProhibitOutbound("N");
    	if(command.getFormerProductId() != null){
        	updateInventoryForReturnCommand.setFormerMerchandiseSerno(command.getFormerBarcode());
        	updateInventoryForReturnCommand.setFormerMerchandiseCode(command.getSkuCode());
        	updateInventoryForReturnCommand.setIsMaintainMerchandise("Y");
        	
        	/*// 修改IMS尺寸信息
        	ModifySingleItemByMCodeCommand modifySingleItemCommand = new ModifySingleItemByMCodeCommand();
        	modifySingleItemCommand.setSku(queryItemReturnByCodeVo.getCode());
        	modifySingleItemCommand.setLenght(queryItemReturnByCodeVo.getLength());
        	modifySingleItemCommand.setWidth(queryItemReturnByCodeVo.getWidth());
        	modifySingleItemCommand.setHeight(queryItemReturnByCodeVo.getHeight());
        	modifySingleItemCommand.setVolume(queryItemReturnByCodeVo.getVolume());
        	modifySingleItemCommand.setWeight(queryItemReturnByCodeVo.getWeight());
        	singleItemService.modifySingleItemByMCode(modifySingleItemCommand);*/
        }
        inventoryService.updateInventoryForReturn(updateInventoryForReturnCommand);
        return SUCCESS;
    }
    
    /**
     * 
     * openapi 接口开发给客户查询商品
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        JSONObject requestJson =  JSON.parseObject(requestMsg.getData().toString());
        PageItemsForOpenApiCommand command = new PageItemsForOpenApiCommand();
        command.setCtx(CommandContext.getContext());
        QueryCompanylCommand queryCompanylCommand = new QueryCompanylCommand();
        queryCompanylCommand.setEmail(command.getCtx().getUsername());
        CustomerInfoVO customerInfoVO = umsCustomerService.queryCompanyByUserName(queryCompanylCommand);
        if (customerInfoVO == null) {
            throw new ApiException(ErrorCode.USER_NOT_FOUND);
        }
        command.setCustomerCode(customerInfoVO.getCode());
        command.setSkuCode(requestJson.getString("skuCode"));
        PageVo pageVo = new PageVo();
        pageVo.setPageNo(requestJson.getInteger("pageNo"));
        pageVo.setPageSize(requestJson.getInteger("pageSize"));
        command.setPageVo(pageVo);
        Page<PageItemForOpenApiVo> page = itemService.pageItemsForOpenApi(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }
    
    /**
     * 
     * MMS3.0更新商品列表有效性
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/updateMmsItemsActive")
    public String updateMmsItemsActive(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        UpdateMmsItemActiveCommand command = JSON.parseObject(requestMsg.getData().toString(),UpdateMmsItemActiveCommand.class);
        List<UpdateMmsItemsCommand> itemList  = command.getItems();
        String isActive = command.getIsActive();
        List<UpdateMmsItemsCommand> updateList  = new ArrayList<UpdateMmsItemsCommand>();

        //拼接错误信息
        List<String> message = new ArrayList<String>();

        //未完成订单列表
        Set<String> orders = new HashSet<String>();
        //存在库存的商品列表
        List<String> items = new ArrayList<String>();

        List<String> orderItems = new ArrayList<String>();

        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if("N".equals(isActive)){
            //校验自验货订单
            QueryOrderNoForWaitInspectionCommand csiCommand = new QueryOrderNoForWaitInspectionCommand();
            csiCommand.setCtx(CommandContext.getContext());
            List<String> merchandises = new ArrayList<String>();
            for (UpdateMmsItemsCommand itemsCommand: itemList) {
                merchandises.add(itemsCommand.getCode());
            }
            csiCommand.setMerchandiseSernos(merchandises);
            List<String> orderNos = csiInboundOrderService.queryOrderNoForWaitInspection(csiCommand);
            if(!orderNos.isEmpty()){
                orders.addAll(orderNos);
            }

            for (UpdateMmsItemsCommand itemsCommand : itemList) {

                ItemCodeCommand itemCodeCommand = new ItemCodeCommand();
                itemCodeCommand.setCode(itemsCommand.getCode());
                ItemVo itemVo = itemService.queryItemByCode(itemCodeCommand);
                if (itemVo == null) {
                    throw new ApiException(ErrorCode.ITEM_NOT_EXIST);
                }

                //oms校验订单,如果校验不通过直接continue
                String thirdCode = itemsCommand.getThirdCode();//第三方编码
                if (StringUtils.isNotBlank(thirdCode)) {
                    GlobalTransferOrderPackagelineCommand lineCommand = new GlobalTransferOrderPackagelineCommand();
                    lineCommand.setProductBarcode(itemsCommand.getCode());
                    lineCommand.setCustomerCode(customer.getCode());
                    List<GlobalTransferOrder> orderVos =
                            globalTransferOrderValidateService.getGlobalTransferByProductBarcode(lineCommand);
                    if (orderVos != null && !orderVos.isEmpty()) {
                        List<String> orderNoList = new ArrayList<String>();
                        for (GlobalTransferOrder order : orderVos) {
                            orderNoList.add(order.getGlobalTransferNo());
                        }

                        orders.addAll(orderNoList);
                        if (orderItems.size() < 5) {
                            orderItems.add(itemVo.getSkuCode());
                        }
                    }
                } else {
                    MerchandiseOrderCommand merchandiseOrderCommand = new MerchandiseOrderCommand();
                    merchandiseOrderCommand.setMerchandiseSerNo(itemsCommand.getCode());
                    merchandiseOrderCommand.setCustomerCode(customer.getCode());
                    List<InboundOrderVo> orderVos =
                            inboundOrderService.getMerchandiseOrder(merchandiseOrderCommand);
                    if (orderVos != null && !orderVos.isEmpty()) {
                        List<String> orderNoList = new ArrayList<String>();
                        for (InboundOrderVo order : orderVos) {
                            orderNoList.add(order.getOrderNo());
                        }
                        orders.addAll(orderNoList);
                        if (orderItems.size() < 5) {
                            orderItems.add(itemVo.getSkuCode());
                        }
                    }
                }


                //IMS校验库存
                QueryOnOrderInventoryCommand queryInventoryCommand = new QueryOnOrderInventoryCommand();
                queryInventoryCommand.setCustomerCode(customer.getCode());
                queryInventoryCommand.setMerchandiseSerno(itemsCommand.getCode());
                boolean isExistInventory =
                        inventoryService.queryOnOrderInventoryByMerchandise(queryInventoryCommand);
                if (isExistInventory) {
                    //IMS库存校验不通过
                    if (items.size() < 5) {
                        items.add(itemVo.getSkuCode());
                    } else {
                        break;
                    }
                }
            }

            if (!orders.isEmpty()) {
                //截取前五
                if (orders.size() > 5) {
                    while(orders.size() > 5) {
                        Iterator<String> orderIterator = orders.iterator();
                        orders.remove(orderIterator.next());
                    }
                }
                //失效失败，存在订单（包括草稿）未处理完成，号码为：xxx\xxx\xxx，请知悉！
                message.add(ContextUtils.getMessage(ErrorCode.INACTIVE_ITEM_OMS, orderItems.toString(), orders.toString()));

            }
            if (!items.isEmpty()) {
                //失效失败，存在库存未处理完成，号码为：xxx\xxx\xxx，请知悉！
                message.add(ContextUtils.getMessage(ErrorCode.INACTIVE_ITEM_IMS, items.toString()));
            }

            if (message.size() != 0) {
                responseMsg.setData(message);
                return SUCCESS;
            } else {
                updateList.addAll(itemList);
            }
        }else{
            for(UpdateMmsItemsCommand itemsCommand: itemList){
                itemsCommand.setCustomerCode(customer.getCode());
            }
            updateList.addAll(itemList);
        }
        
        if(!updateList.isEmpty()){
            UpdateMmsItemActiveCommand updateCommand = new UpdateMmsItemActiveCommand();
            updateCommand.setIsActive(isActive);
            updateCommand.setItems(updateList);
            updateCommand.setCtx(CommandContext.getContext());
            itemService.updateItemsActive(updateCommand);
        }

        return SUCCESS;
    }
    
    /**
     * 
     * MMS3.0更新商品列表有效性
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/updateMmsReturnItemsActive")
    public String updateMmsReturnItemsActive(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        UpdateMmsReturnItemActiveCommand command = JSON.parseObject(requestMsg.getData().toString(),UpdateMmsReturnItemActiveCommand.class);
        List<UpdateMmsReturnItemsCommand> itemList  = command.getItems();
        String isActive = command.getIsActive();
        
        List<String> allIdList  = new ArrayList<String>();
        List<String> updateIdList  = new ArrayList<String>();
        List<UpdateMmsItemsCommand> updateList  = new ArrayList<UpdateMmsItemsCommand>();
        // 获取客户编码
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if("N".equals(isActive)){
            for(UpdateMmsReturnItemsCommand itemsCommand: itemList){
                ItemReturnVo returnVo = itemService.getReturnById(itemsCommand);
                if(returnVo == null){
                    continue;
                }
                
                List<ItemReturnVo> resultVos = new ArrayList<ItemReturnVo>();
                if(StringUtils.isNotBlank(returnVo.getOriginalCode())){
                    //通过originalCode找出所有记录
                    GetByOriginalCodeCommand getByOriginalCodeCommand = new GetByOriginalCodeCommand();
                    getByOriginalCodeCommand.setCustomerCode(customer.getCode());
                    getByOriginalCodeCommand.setOriginalCode(returnVo.getOriginalCode());
                    getByOriginalCodeCommand.setIsActive("Y");
                    List<ItemReturnVo> returnVos = itemService.getByOriginalCode(getByOriginalCodeCommand);
                    resultVos.addAll(returnVos);
                    allIdList.add(returnVo.getOriginalCode()+"(return)");
                }else{
                    resultVos.add(returnVo);//当前选中记录，能展示就肯定是维护过了
                    allIdList.add(returnVo.getSkuCode());
                }
                
                //oms校验订单,如果校验不通过直接continue
                List<InboundOrderVo> orderVos = null;
                for(ItemReturnVo tmpReturnVo : resultVos){
                    MerchandiseOrderCommand merchandiseOrderCommand = new MerchandiseOrderCommand();
                    merchandiseOrderCommand.setMerchandiseSerNo(tmpReturnVo.getCode());
                    merchandiseOrderCommand.setCustomerCode(customer.getCode());
                    orderVos = inboundOrderService.getMerchandiseOrder(merchandiseOrderCommand);
                    if(orderVos != null && !orderVos.isEmpty()){
                        break;
                    }
                }
                if(orderVos != null && !orderVos.isEmpty()){
                    continue;
                }
                
                //IMS校验库存
                boolean isExistInventory = false;
                for(ItemReturnVo tmpReturnVo : resultVos){
                    QueryOnOrderInventoryCommand queryInventoryCommand = new QueryOnOrderInventoryCommand();
                    queryInventoryCommand.setCustomerCode(customer.getCode());
                    queryInventoryCommand.setMerchandiseSerno(tmpReturnVo.getCode());
                    isExistInventory = 
                            inventoryService.queryOnOrderInventoryByMerchandise(queryInventoryCommand);
                    if(isExistInventory){
                        break;//IMS库存校验不通过
                    }
                }
                if(isExistInventory){
                    continue;//IMS库存校验不通过
                }
                
                for(ItemReturnVo tmpReturnVo : resultVos){
                    UpdateMmsItemsCommand updateItemsCommand = new UpdateMmsItemsCommand();
                    updateItemsCommand.setCode(tmpReturnVo.getCode());
                    updateItemsCommand.setCustomerCode(customer.getCode());
                    updateList.add(updateItemsCommand);
                }
                if(StringUtils.isNotBlank(returnVo.getOriginalCode())){
                    updateIdList.add(returnVo.getOriginalCode()+"(return)");
                }else{
                    updateIdList.add(returnVo.getSkuCode());
                }
            }
        }else{
            for(UpdateMmsReturnItemsCommand itemsCommand: itemList){
                ItemReturnVo returnVo = itemService.getReturnById(itemsCommand);
                if(returnVo == null){
                    continue;
                }
                if(StringUtils.isNotBlank(returnVo.getOriginalCode())){
                    allIdList.add(returnVo.getOriginalCode()+"(return)");
                    updateIdList.add(returnVo.getOriginalCode()+"(return)");
                }else{
                    allIdList.add(returnVo.getSkuCode());
                    updateIdList.add(returnVo.getSkuCode());
                }
                
                List<ItemReturnVo> resultVos = new ArrayList<ItemReturnVo>();
                if(StringUtils.isNotBlank(returnVo.getOriginalCode())){
                    //通过originalCode找出所有记录
                    GetByOriginalCodeCommand getByOriginalCodeCommand = new GetByOriginalCodeCommand();
                    getByOriginalCodeCommand.setCustomerCode(customer.getCode());
                    getByOriginalCodeCommand.setOriginalCode(returnVo.getOriginalCode());
                    getByOriginalCodeCommand.setIsActive("N");
                    List<ItemReturnVo> returnVos = itemService.getByOriginalCode(getByOriginalCodeCommand);
                    resultVos.addAll(returnVos);
                }else{
                    resultVos.add(returnVo);
                }
                
                for(ItemReturnVo tmpReturnVo: resultVos){
                    UpdateMmsItemsCommand updateItemsCommand = new UpdateMmsItemsCommand();
                    updateItemsCommand.setCode(tmpReturnVo.getCode());
                    updateItemsCommand.setCustomerCode(customer.getCode());
                    updateList.add(updateItemsCommand);
                }
            }
        }
        
        if(!updateList.isEmpty()){
            UpdateMmsItemActiveCommand updateCommand = new UpdateMmsItemActiveCommand();
            updateCommand.setIsActive(isActive);
            updateCommand.setItems(updateList);
            updateCommand.setCtx(CommandContext.getContext());
            itemService.updateReturnItemsActive(updateCommand);
        }
        
        List<String> failIdList = new ArrayList<String>();
        for(String id: allIdList){
            if(!updateIdList.isEmpty()){
                if(!updateIdList.contains(id)){
                    failIdList.add(id);
                }
            }else{
                failIdList.add(id);
            }
        }
        
        responseMsg.setData(failIdList);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/clearItemSpecification")
    public String clearItemSpecification(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        ModifyClearItemSpecificationCommand command = JSON.parseObject(requestMsg.getData().toString(), ModifyClearItemSpecificationCommand.class);
        CustomerInfoVO customerInfo = this.getContextCustomerInfo();
        //oms校验订单
        MerchandiseOrderCommand merchandiseOrderCommand = new MerchandiseOrderCommand();
        merchandiseOrderCommand.setMerchandiseSerNo(command.getCode());
        merchandiseOrderCommand.setCustomerCode(customerInfo.getCode());
        List<InboundOrderVo> orderVos = inboundOrderService.getMerchandiseOrder(merchandiseOrderCommand);
        if(orderVos != null && !orderVos.isEmpty()){
            throw new ApiException(ErrorCode.ITEM_IN_USE);
        }

        //自验货校验订单中的商品
        QueryOrderNoForWaitInspectionCommand csiCommand = new QueryOrderNoForWaitInspectionCommand();
        csiCommand.setCtx(CommandContext.getContext());
        List<String> merchandiseSernos = new ArrayList<String>();
        merchandiseSernos.add(command.getCode());
        csiCommand.setMerchandiseSernos(merchandiseSernos);
        List<String> orderNos = csiInboundOrderService.queryOrderNoForWaitInspection(csiCommand);
        if(!orderNos.isEmpty()){
            throw new MMSException(ErrorCode.ITEM_IN_USE);
        }

        command.setCustomerCode(customerInfo.getCode());
        itemService.modifyClearItemSpecification(command);
        return SUCCESS;
    }

    /**
     * 接收供应商那边的海关建议申报信息
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/auditCustomsInfoBySku")
    public String auditCustomsInfoBySku(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ReceiveRecommendDeclareInfoCommand command = JSON.parseObject(requestMsg.getData().toString(), ReceiveRecommendDeclareInfoCommand.class);
        itemService.receiveRecommendDeclareInfo(command);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/queryLikeSkuCode")
    public String queryLikeSkuCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        QueryLikeSkuCodeCommand command = JSON.parseObject(requestMsg.getData().toString(), QueryLikeSkuCodeCommand.class);
        CustomerInfoVO customerInfo = this.getContextCustomerInfo();
        command.setCustomerCode(customerInfo.getCode());
        List<ItemVo> itemVos = itemService.queryLikeSkuCode(command);
        responseMsg.setData(itemVos);
        return SUCCESS;
    }
    
    @RequestMapping(value = "/batchModifySkuInternetSite")
    public String batchModifySkuInternetSite(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg){
        BatchModifySkuInternetSiteCommand command = JSON.parseObject(requestMsg.getData().toString(), BatchModifySkuInternetSiteCommand.class);
        CustomerInfoVO customerInfo = this.getContextCustomerInfo();
        command.setCustomerCode(customerInfo.getCode());
        List<String> itemVos = itemService.batchModifySkuInternetSite(command);
        responseMsg.setData(itemVos);
        return SUCCESS;
    }
	
	    /** 从上下文中获取客户信息 */
    private CustomerInfoVO getContextCustomerInfo() {
        QueryCompanylCommand userCommand = new QueryCompanylCommand();
        userCommand.setEmail(CommandContext.getContext().getUsername());
        CustomerInfoVO customer = umsCustomerService.queryCompanyByUserName(userCommand);
        if(customer == null) {
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }
        return customer;
    }
	
    /**
     * 退货上架策略维护，分页查询接口
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/queryItemForShelfStrategy")
    public String queryItemForShelfStrategy(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	PageItemsCommand command = JSON.parseObject(requestMsg.getData().toString(), PageItemsCommand.class);
    	CustomerInfoVO customer = getContextCustomerInfo();
    	command.setCustomerCode(customer.getCode());
        Page<ItemPagesVo> page = itemService.pageItemsForShelfStategy(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
    	
    	return SUCCESS;
    }
	
    /**
     * 维护商品退货上架策略
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/updateItemsShelfStrategy")
    public String updateItemsShelfStrategy(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        ModifySkuShelfStrategyCommand command = JSON.parseObject(requestMsg.getData().toString(), ModifySkuShelfStrategyCommand.class);
        command.setCtx(CommandContext.getContext());
        CustomerInfoVO customer = getContextCustomerInfo();
        for (ItemShelfStrategyVo itemVo:command.getItems()) {
        	itemVo.setCustomerCode(customer.getCode());
        }
        itemService.modifyItemShelfStrategy(command);
        return SUCCESS;
    }
    
    /**
     * 获取维护退货上架策略商品数量
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping("/getSetCountForShelf")
    public String getSetCountForShelf(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        CustomerInfoVO customer = getContextCustomerInfo();
        CodeCommand command = new CodeCommand();
        command.setCode(customer.getCode());
        ItemSetUpShelfCountVo vo = itemService.getSetCountForShelf(command);
        responseMsg.setData(vo);
        return SUCCESS;
    }
    
    /**
     * 导入商品退货上架策略
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/importItemShelfStrategy")
    public String importItemShelfStrategy(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	ImportSkuShelfStrategyCommand command = JSON.parseObject(requestMsg.getData().toString(), ImportSkuShelfStrategyCommand.class);
        command.setCtx(CommandContext.getContext());
        CustomerInfoVO customer = getContextCustomerInfo();
        command.setCustomerCode(customer.getCode());
        List<String> errorList = itemService.importItemsForModifyShelf(command);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("errorList", errorList);
        responseMsg.setData(dataMap);
        return SUCCESS;
    }
    
    /**
     * 模糊查询商品信息
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getMMSList")
    public String getMMSList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	QueryMMSItemCommand command = JSON.parseObject(requestMsg.getData().toString(), QueryMMSItemCommand.class);
    	CustomerInfoVO customer = getContextCustomerInfo();
    	command.setCustomerCode(customer.getCode());
        List<String> items = itemService.queryItemsForShelf(command);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("itemList", items);
        responseMsg.setData(dataMap);
    	
    	return SUCCESS;
    }
    
    @RequestMapping(value = "/queryItemsBySkuCode")
    public String queryItemsBySkuCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	JSONObject requestJson =  JSON.parseObject(requestMsg.getData().toString());
    	PageItemsCommand command = new PageItemsCommand();
    	CustomerInfoVO customer = getContextCustomerInfo();
    	command.setCustomerCode(customer.getCode());
    	command.setSkuCode(requestJson.getString("skuCode"));
    	command.setPageParams(requestJson.getObject("pageParams", PageVo.class));
        Page<ItemPagesVo> page = itemService.pageAllItems(command);
        if (page != null) {
            Map<String, Object> data = this.getPageParams(page);
            data.put("list", page.content);
            responseMsg.setData(data);
        }
    	
    	return SUCCESS;
    }
    
    /**
     * 导出卖家所有商品(包含正常商品及已维护的退货商品)
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/exportAllItems")
    public String exportAllItems(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	QueryMMSItemCommand command = JSON.parseObject(requestMsg.getData().toString(), QueryMMSItemCommand.class);
    	CustomerInfoVO customer = getContextCustomerInfo();
    	command.setCustomerCode(customer.getCode());
        String fileUrl = itemService.exportAllItemsForShelfStrategy(command);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("fileUrl", fileUrl);
        responseMsg.setData(dataMap);
    	
    	return SUCCESS;
    }
    
    /**
     * 导出卖家所有商品(包含正常商品及已维护的退货商品)
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/exportSeletedItems")
    public String exportSeletedItems(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
    	ExportSkuShelfStrategyCommand command = JSON.parseObject(requestMsg.getData().toString(), ExportSkuShelfStrategyCommand.class);
        command.setCtx(CommandContext.getContext());
        CustomerInfoVO customer = getContextCustomerInfo();
        for (ItemShelfStrategyVo itemVo:command.getItemList()) {
        	itemVo.setCustomerCode(customer.getCode());
        }
        String fileUrl = itemService.exportSeletedItemsForShelfStrategy(command);
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("fileUrl", fileUrl);
        responseMsg.setData(dataMap);
    	
    	return SUCCESS;
    }
}
